package cn.pzhu.services.admin;

import cn.pzhu.model.Category;
import cn.pzhu.model.Role;
import cn.pzhu.services.BaseServices;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dongp on 2016/4/25.
 */
public class CategoryServices extends BaseServices {

    public List<Category> ajaxQuery() {
        List<Category> categories = Category.dao.find("select * from category");
        return categories;
    }

    public List<Category> ajaxQueryPage(String pageNumber, String pageSize, String search) {
        ArrayList arrts = new ArrayList();
        Map<String,Object> map = new HashMap<>();

        List<Category> categories = Category.dao.find("select c.* from category c where c.typeName like '%" + search + "%' limit "
                + pageNumber + "," + pageSize);
        arrts.add(categories);

        Category category = Category.dao.findFirst("select count(*) total from category c where c.typeName like '%"+search+"%'");
        Long total = category.getLong("total").longValue();
        map.put("total", total);
        arrts.add(map);
        return arrts;
    }

    public boolean ajaxUpdate(String categoryID, String typeName, Integer typeVal) {

        boolean result = Category.dao.findById(categoryID).set("typeName", typeName).set("typeVal",typeVal).update();

        return result;
    }

    public boolean ajaxAdd(String typeName, Integer typeVal) {

        // 检查是否重复
        Category category =  Category.dao.findFirst("select count(*) count from category where typeName = ?",typeName);
        Long count = category.getLong("count").longValue();
        if(count > 0) {
            return false;
        }

        // 保存
        boolean result = new Category().set("typeName", typeName).set("typeVal",typeVal).save();
        return result;
    }

    public boolean ajaxDel(String categoryID) {
        return Category.dao.deleteById(categoryID);
    }

}
